package com.niit.gjl.avgpricebyyear;

import com.niit.util.DataConvUtils;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.text.DecimalFormat;

public class AvgPriceByYearReducer extends Reducer<Text, Text, Text, Text> {
    private Text outv = new Text();
    private int priceTotalByComYear;
    private double totalPriceSum;

    /**
     * reduce阶段的核心业务逻辑（根据相同的年份，进行统计，得出相同年份的平均价格(总价)，然后输出）
     *
     * @param key     年份, eg: 2016年建造...
     * @param values  总价, eg: 95...
     * @param context
     * @throws IOException
     * @throws InterruptedException
     */
    @Override
    protected void reduce(Text key, Iterable<Text> values, Reducer<Text, Text, Text, Text>.Context context) throws IOException, InterruptedException {
        for (Text value : values) {
            priceTotalByComYear++;
            totalPriceSum += DataConvUtils.strToDouble(value.toString(), 0);
        }
        DecimalFormat df = new DecimalFormat("#.##");// 保留2位小数
        String formattedNumber = df.format(totalPriceSum / priceTotalByComYear);
        outv.set(formattedNumber + "w");
        context.write(key, outv);
        priceTotalByComYear = 0;
        totalPriceSum = 0;

    }

}
